package com.xingfei.blog.controller.validate;

import com.xingfei.blog.common.JsonResult;
import com.xingfei.blog.constants.ErrorConstants;
import com.xingfei.blog.service.WebUserInfoService;
import com.xingfei.blog.vo.UserInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.websocket.server.PathParam;
import java.util.Objects;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: chenxingfei
 * @time: 2017/3/18  15:11
 * To change this template use File | Settings | File Templates.
 */
@Controller
@RequestMapping("validate")
public class ValidateController {

    @Autowired
    private WebUserInfoService webUserInfoService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 根据条件校验是否重复
     * @param userInfoVO
     * @return
     */
    @GetMapping(value = "/checkRepetition")
    @ResponseBody
    public JsonResult checkUserName(UserInfoVO userInfoVO) {
        JsonResult jsonResult = new JsonResult(ErrorConstants.SERVER_ERROR,"校验失败，请重试！");
        if (userInfoVO != null) {
            //查询数据，校验是重复
            boolean result = webUserInfoService.getUserInfoByCondition(userInfoVO);
            if(result){
                jsonResult = new JsonResult(ErrorConstants.SERVER_SUCCESS,"校验成功");
            }else{
                jsonResult = new JsonResult(ErrorConstants.RESULT_USERNAME_REPET,"已存在,请更换！");
            }
        }
        return jsonResult;
    }

    /**
     * 校验验证码
     * @param authcode 验证码
     * @param phone 用户手机号
     * @return
     */
    @GetMapping(value = "/checkAuthCode")
    @ResponseBody
    public JsonResult checkAuthCode(@PathParam("authcode") String authcode, @PathParam("phone") String phone) {
        JsonResult jsonResult = new JsonResult(ErrorConstants.SERVER_ERROR, "验证码校验失败，请重试！");
        if (StringUtils.isNotBlank(authcode) && StringUtils.isNotBlank(phone)) {
            //查询数据，校验是重复
            final String code = this.stringRedisTemplate.opsForValue().get(phone);
            if (Objects.equals(authcode, code)) {
                jsonResult = new JsonResult(ErrorConstants.SERVER_SUCCESS, "验证码输入正确");
            } else {
                jsonResult = new JsonResult(ErrorConstants.RESULT_PHONE_REPET, "验证码输入错误，请确认手机验证码是否一致！");
            }
        }
        return jsonResult;
    }
}
